import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:share_fit/app/components/back_btn_icon.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/generated/locales.g.dart';
import 'package:share_fit/app/models/home/edit_widget_item.dart';

import 'logic.dart';

class EditWidgetPage extends StatelessWidget {
  EditWidgetPage({Key? key}) : super(key: key);

  final logic = Get.put(EditWidgetLogic());
  final state = Get.find<EditWidgetLogic>().state;

  static double bodyPadding = 30.w;
  static double gridSpacing = 30.w;

  @override
  Widget build(BuildContext context) {
    // logic.initHasList(context);

    return Scaffold(
      appBar: AppBar(
        leading: BackBtnIcon(onTap: () => logic.goBack(context)),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: EdgeInsets.only(left: 40.w, right: 40.w, top: 40.w, bottom: 300.h),
          child: _createEditWidgetPage(context),
        ),
      ),
    );

    // return PopScope(
    //   canPop: false,
    //   onPopInvoked: (value) => logic.onPopInvoked(context, value),
    //   child: Scaffold(
    //     appBar: AppBar(
    //       leading: BackBtnIcon(onTap: () => logic.goBack(context)),
    //     ),
    //     body: SingleChildScrollView(
    //       child: Padding(
    //         padding: EdgeInsets.only(left: 40.w, right: 40.w, top: 40.w, bottom: 300.h),
    //         child: _createEditWidgetPage(context),
    //       ),
    //     ),
    //   ),
    // );
  }

  Widget _createEditWidgetPage(BuildContext context) {
    return Column(
      children: [
        Container(
            margin: EdgeInsets.only(bottom: 72.h),
            alignment: Alignment.topLeft,
            child: Text(LocaleKeys.edit_widgets_existing_title.ts,
                style: TextStyle(
                  fontSize: 48.sp,
                ))),

        /// 已有小组件区
        GetBuilder<EditWidgetLogic>(
          builder: (editLogic) {
            return GridView.builder(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemCount: state.hasList.length,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                mainAxisSpacing: gridSpacing,
                crossAxisSpacing: gridSpacing,
                childAspectRatio: 2.5,
              ),
              itemBuilder: (context, index) {
                return _buildDraggable(index);
              },
            );
          },
        ),

        /// 拖动提示语
        Container(
            margin: EdgeInsets.only(bottom: 85.w, top: 57.w),
            alignment: Alignment.center,
            child: Text(
              LocaleKeys.edit_widgets_drag_title.ts,
              style: TextStyle(fontSize: 40.sp),
            )),
        Container(
          margin: EdgeInsets.only(bottom: 73.w),
          alignment: const Alignment(-1, 0),
          child: Text(LocaleKeys.edit_widgets_available_title.ts, style: TextStyle(fontSize: 48.sp)),
        ),

        /// 可添加的小组件
        GetBuilder<EditWidgetLogic>(
          builder: (editLogic) {
            return GridView.builder(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemCount: state.sourceList.length,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                mainAxisSpacing: gridSpacing,
                crossAxisSpacing: gridSpacing,
                childAspectRatio: 2.5,
              ),
              itemBuilder: (context, index) {
                return _buildItem(state.sourceList[index]);
              },
            );
          },
        )
      ],
    );
  }

  //生成widget列表
  List<Widget> _buildDraggableChildren() {
    final List<Widget> list = [];
    for (int x = 0; x < state.hasList.length; x++) {
      list.add(_buildDraggable(x));
    }
    return list;
  }

  //绘制一个可拖拽的控件。
  Widget _buildDraggable(int index) {
    return AnimatedContainer(
        duration: const Duration(microseconds: 100),
        // transform: Matrix4.translationValues(2.0, 4.0, 0.0),
        child: LayoutBuilder(builder: (context, constraint) {
          // 返回一个Draggable
          return LongPressDraggable(
            data: index,
            childWhenDragging: state.showItemWhenCovered.value ? _buildItem(state.hasList[index]) : null,

            onDragStarted: () {
              //开始拖动，备份数据源
              state.backupHasList = state.hasList.sublist(0);
              print('item $index ---------------------------onDragStarted');
            },

            onDraggableCanceled: (Velocity velocity, Offset offset) {
              print('item $index ---------------------------onDraggableCanceled,velocity = $velocity,offset = $offset');
              //拖动取消，还原数据源

              state.showItemWhenCovered.value = false;
              state.hasList = state.backupHasList.sublist(0);
            },

            onDragCompleted: () {
              //拖动完成，刷新状态，重置willAcceptIndex
              print("item $index ---------------------------onDragCompleted");
              state.showItemWhenCovered.value = false;
            },

            // 必须要一个Material，不然拖动时Text会有双下划线
            feedback: Material(
              child: _buildItem(state.hasList[index]),
            ),
            child: DragTarget<int>(
              builder: (BuildContext context, List<int?> candidateData, List<dynamic> rejectedData) {
                return _buildItem(state.hasList[index]);
              },
              onAccept: (data) => logic.onDragAccept(data, index),
              //手指拖着一个widget从另一个widget头上滑走时会调用
              onLeave: (data) {
                //这里应该还可以优化，当用户滑出而又没有滑入某个item的时候 可以重新排列  让当前被拖走的item的空白被填满
                print('$data is Leaving item $index');
              },
              //接下来松手 是否需要将数据给这个widget？  因为需要在拖动时改变UI，所以在这里直接修改数据源
              onWillAccept: (data) {
                print('$index will accept item $data');
                return true;
              },
            ),
          );
        }));
  }

  Widget _buildItem(EditWidgetItem item) {
    Image action = item.action == 'add'
        ? Image.asset('assets/images/home/widget_add_btn.png', height: 64.w, width: 64.w)
        : Image.asset('assets/images/home/widget_remove_btn.png', height: 64.w, width: 64.w);

    return GestureDetector(
      onTap: () => item.action == 'add' ? logic.addToHasList(item) : logic.removeFromHasList(item),
      child: Container(
        width: item.width,
        height: item.height,
        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(60.r)),
        child: Stack(
          alignment: Alignment.centerLeft,
          children: [
            Positioned(
              child: Row(
                children: [
                  SizedBox(width: 48.w),
                  Expanded(child: _wrapItemTitle(item)),
                  Image.asset(item.image!, height: 100.w, width: 100.w),
                  SizedBox(width: 69.w),
                ],
              ),
            ),
            Positioned(right: 0, top: 0, child: action),
          ],
        ),
      ),
    );
  }

  _wrapItemTitle(EditWidgetItem item) {
    if (item.title.length > 10) {
      var titleSplit = item.title.split(' ');
      return Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(titleSplit[0], style: TextStyle(fontSize: 50.sp)),
          Text(titleSplit[1], style: TextStyle(fontSize: 45.sp), overflow: TextOverflow.ellipsis),
        ],
      );
    } else {
      return Text(item.title, style: TextStyle(fontSize: 50.sp));
    }
  }
}
